package com.wb.mas.ui.order;

import android.app.Application;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.wb.mas.BR;
import com.wb.mas.R;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.OrderListEntity;
import com.wb.mas.entity.OrderListResponse;
import com.wb.mas.ui.base.viewmodel.ToolbarViewModel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * Copyright (C) 2018,
 * OrderViewModel
 * <p>
 * Description
 * 订单
 *
 * @author mwl
 * @version 1.0
 * <p>
 * Ver 1.0, 2019-04-30, mwl, Create file
 */
public class OrderViewModel extends ToolbarViewModel {

    public UIChangeObservable uc = new UIChangeObservable();

    public int type;

    public static final int PAGE_NUM = 10;

    public int page = 1;

    /**
     * 是否可以加载更多
     */
    public ObservableField<Boolean> isMore = new ObservableField<>();

    /**
     * 是否没数据
     */
    public ObservableField<Boolean> isEmpty = new ObservableField<>();


    public OrderViewModel(@NonNull Application application, DemoRepository model) {
        super(application, model);
    }

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent<>();
        //上拉加载完成
        public SingleLiveEvent finishLoadmore = new SingleLiveEvent<>();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
        showDialog();
        getOrder(false);
    }

    private void init() {
        if (type == OrderActivity.ORDER_BORROW) {
            isMore.set(false);
            setTitleText(getString(R.string.order_borrow_title));
        } else {
            isMore.set(true);
            setTitleText(getString(R.string.order_compete_title));
        }
        setRightIconVisible(View.GONE);
    }


    //给RecyclerView添加ObservableList
    public ObservableList<OrderItemViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<OrderItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.recycle_order);
    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            page = 1;
            if (type == OrderActivity.ORDER_COMPLETE) {
                isMore.set(true);
            }

            getOrder(true);
        }
    });

    //上拉加载
    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (type == OrderActivity.ORDER_COMPLETE) {
                page++;
                getOrder(false);
            }
        }
    });


    private void getOrder(final boolean isRefush) {
        Map<String, Object> map = new HashMap<>();
        map.put("limit", String.valueOf(PAGE_NUM));
        map.put("page", String.valueOf(page));
        addSubscribe(model.getOrderPageList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<OrderListResponse>() {
                    @Override
                    public void accept(OrderListResponse orderResponse) throws Exception {
                        dismissDialog();
                        uc.finishRefreshing.call();
                        uc.finishLoadmore.call();
                        if (isRefush) {
                            observableList.clear();
                        }
                        if (type == OrderActivity.ORDER_BORROW || orderResponse.getData() == null || orderResponse.getData().size() < PAGE_NUM) {
                            isMore.set(false);
                        }
                        if (orderResponse.getData() != null && orderResponse.getData().size() > 0) {
                            setDatas(orderResponse.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.w(throwable.getMessage());
                    }
                }));
    }

    private void setDatas(List<OrderListEntity> entities) {
        if (type == OrderActivity.ORDER_COMPLETE) {
            if (page == 1) {
                if (entities.get(0).isNoCompleteStatus()) {
                    entities.remove(0);
                }
            }
            for (OrderListEntity entity : entities) {
                addItem(entity);
            }
        } else {
            if (entities.get(0).isNoCompleteStatus()) {
                addItem(entities.get(0));
            }
        }

        if (entities.size()==0){
            isEmpty.set(true);
        }else{
            isEmpty.set(false);
        }
    }


    private void addItem(OrderListEntity orderEntity) {
        OrderItemViewModel itemViewModel = new OrderItemViewModel(this, orderEntity);
        observableList.add(itemViewModel);
    }



//    private void getNoCompleteOrder(final boolean isRefush) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("type", String.valueOf(0));
//        Observable<OrderResponse> responseObservable1 = model.getOrderInfoList(map);
//
//        Map<String, Object> map2 = new HashMap<>();
//        map2.put("type", String.valueOf(1));
//        Observable<OrderResponse> responseObservable2 = model.getOrderInfoList(map2);
//
//        Map<String, Object> map3 = new HashMap<>();
//        map3.put("type", String.valueOf(6));
//        Observable<OrderResponse> responseObservable3 = model.getOrderInfoList(map3);
//
//        Map<String, Object> map4 = new HashMap<>();
//        map4.put("type", String.valueOf(7));
//        Observable<OrderResponse> responseObservable4 = model.getOrderInfoList(map4);
//
//
//        addSubscribe(Observable.zip(responseObservable1, responseObservable2, responseObservable3, responseObservable4, new Function4<OrderResponse, OrderResponse, OrderResponse, OrderResponse, List<OrderEntity>>() {
//            @Override
//            public List<OrderEntity> apply(OrderResponse orderResponse, OrderResponse orderResponse2, OrderResponse orderResponse3, OrderResponse orderResponse4) throws Exception {
//                List<OrderEntity> orderEntities = new ArrayList<>();
//                if (orderResponse != null && orderResponse.getData() != null) {
//                    orderEntities.addAll(orderResponse.getData());
//                }
//                if (orderResponse2 != null && orderResponse2.getData() != null) {
//                    orderEntities.addAll(orderResponse2.getData());
//                }
//                if (orderResponse3 != null && orderResponse3.getData() != null) {
//                    orderEntities.addAll(orderResponse3.getData());
//                }
//                if (orderResponse4 != null && orderResponse4.getData() != null) {
//                    orderEntities.addAll(orderResponse4.getData());
//                }
//                return orderEntities;
//            }
//        }).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<List<OrderEntity>>() {
//                    @Override
//                    public void accept(List<OrderEntity> orderEntities) throws Exception {
//                        if (isRefush) {
//                            uc.finishRefreshing.call();
//                        } else {
//                            dismissDialog();
//                        }
//                        setDatas(orderEntities);
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        if (isRefush) {
//                            uc.finishRefreshing.call();
//                        } else {
//                            dismissDialog();
//                        }
//                        KLog.w(throwable.getMessage());
//                    }
//                }));
//
//
//    }
//
//
//    private void getCompleteOrder(final boolean isRefush) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("type", String.valueOf(2));
//        map.put("page", 1);
//        map.put("limit", String.valueOf(1000));
//        Observable<OrderPageResponse> responseObservable1 = model.getOrderInfoPage(map);
//
//        Map<String, Object> map2 = new HashMap<>();
//        map2.put("type", String.valueOf(3));
//        map2.put("page", 1);
//        map2.put("limit", String.valueOf(1000));
//        Observable<OrderPageResponse> responseObservable2 = model.getOrderInfoPage(map2);
//
//        addSubscribe(Observable.zip(responseObservable1, responseObservable2, new BiFunction<OrderPageResponse, OrderPageResponse, List<OrderEntity>>() {
//            @Override
//            public List<OrderEntity> apply(OrderPageResponse orderResponse, OrderPageResponse orderResponse2) throws Exception {
//                List<OrderEntity> orderEntities = new ArrayList<>();
//                if (orderResponse != null && orderResponse.getData() != null && orderResponse.getData().records != null) {
//                    orderEntities.addAll(orderResponse.getData().records);
//                }
//                if (orderResponse2 != null && orderResponse2.getData() != null && orderResponse2.getData().records != null) {
//                    orderEntities.addAll(orderResponse2.getData().records);
//                }
//                return orderEntities;
//            }
//        }).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<List<OrderEntity>>() {
//                    @Override
//                    public void accept(List<OrderEntity> orderEntities) throws Exception {
//                        if (isRefush) {
//                            uc.finishRefreshing.call();
//                        } else {
//                            dismissDialog();
//                        }
//                        setDatas(orderEntities);
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        if (isRefush) {
//                            uc.finishRefreshing.call();
//                        } else {
//                            dismissDialog();
//                        }
//                        KLog.w(throwable.getMessage());
//                    }
//                }));
//
//    }


    /**
     * 获取条目下标
     *
     * @param orderItemViewModel
     * @return
     */
    public int getItemPosition(OrderItemViewModel orderItemViewModel) {
        return observableList.indexOf(orderItemViewModel);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
